﻿using System;
using System.IO;
using System.Text;

namespace OmniKits.Core
{
    using NullGuard;

    // borrowed the idea from http://damieng.com/blog/2008/07/30/linq-to-sql-log-to-debug-window-file-memory-or-multiple-writers
    [NullGuard(ValidationFlags.None)]
    public sealed class ActionLineWriter : TextWriter
    {
#pragma warning disable 1591

        private readonly Action<string> _Action;
        private readonly StringBuilder _Buffer = new StringBuilder();
        private bool _CarriageReturnHappened = false;

        public ActionLineWriter(Action<string> action)
        {
            _Action = action;
        }

        private void FlushLine()
        {
            if (_Action != null)
                _Action(_Buffer.ToString());
            _Buffer.Clear();
        }

        public override void Write(char value)
        {
            switch (value)
            {
                case '\n':
                    if (_CarriageReturnHappened)
                        _CarriageReturnHappened = false;
                    else
                        FlushLine();
                    return;
                case '\r':
                    _CarriageReturnHappened = true;
                    FlushLine();
                    return;
            }

            _CarriageReturnHappened = false;
            _Buffer.Append(value);
        }

        public override Encoding Encoding => Defaults.UnicodeEncoding;
    }
}
